<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="app">
      <a href="/home">首页</a>
      <a href="/about">关于</a>

      <div class="router-view"></div>
    </div>

    <script>
      // history模式
      const routerView1 = document.querySelector('.router-view')
      // 1.获取所有a元素,获取href属性
      const eleArr = document.getElementsByTagName('a')
      for (const item of eleArr) {
        item.addEventListener('click', e => {
          // 阻止超链接默认行为
          e.preventDefault()
          let href = item.getAttribute('href')
          history.pushState({}, '', href)
          urlChanged()
        })
      }

      // 前进后退都会触发
      window.addEventListener('popstate', urlChanged)

      function urlChanged() {
        console.log(location.pathname)
        switch (location.pathname) {
          case '/home':
            routerView1.innerHTML = '首页'
            break
          case '/about':
            routerView1.innerHTML = '关于页'
            break
          default:
            routerView1.innerHTML = ''
            break
        }
      }
    </script>
  </body>
</html>
